package com.inspur.resourcequery;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RadioButton;
import android.widget.Toast;

import com.inspur.common.BaseActivity;
import com.inspur.common.MyApplication;
import com.inspur.common.domain.RequestInfo;
import com.inspur.common.utils.URLManager;
import com.inspur.resourcequery.model.ResData;

public class ErrorReportActivity extends BaseActivity implements OnClickListener{

	public ResData models;
	//拍照文件
	private String fileName;
	//拍照文件URI
	private Uri imageUri;
	//是否与现场一致-是
	private RadioButton consistentRadio;
	//备注
	private EditText remarkEdt;
	//照片
	private ImageView photoImv;
	//拍照按钮
	private Button photoBtn;
	//提交按钮
	private Button submitBtn;

	private MyApplication application;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		application = (MyApplication)this.getApplication();
		
		models = (ResData) getIntent().getSerializableExtra("data");
		actionBar.setTitle("错误上报");

	}

	/**
	 * 上报
	 */
	protected void report() {
		RequestInfo req = new RequestInfo();
		// RequestInfo.method = "GET";
		req.context = ErrorReportActivity.this;
		
		if(fileName != null){
			Map<String, File> fileMap = new HashMap<String, File>();
			fileMap.put("file", new File(fileName));
			req.fileMap = fileMap;
			req.requestUrl = URLManager.URL + URLManager.CHECK_ERROR_REPORT;
		}  else {
			req.requestUrl = URLManager.URL + URLManager.CHECK_ERROR_REPORT_NOFILE;
		}
		
		try {
			JSONObject condition = new JSONObject();
			condition.put("ResClassName", models.getResclassenname());
			condition.put("ResClassNameCn", models.getResclasscnname() == null ? "" :  models.getResclasscnname());
			condition.put("consistent", consistentRadio.isChecked() ? "一致" : "不一致");
			condition.put("name", models ==null ? "" : models.getName());
			condition.put("creator", application.getUserInfo().getUseraccount());
			condition.put("content", remarkEdt.getText());
			condition.put("int_id", models.getInt_id());
			req.params = condition.toString();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.getDataFromServer(req, new DataCallback<String>() {
			@Override
			public void processData(String paramObject) {
				Log.d("paramObject:", paramObject);
				if("0".equals(paramObject)){
					Toast.makeText(ErrorReportActivity.this, "上报失败！", Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(ErrorReportActivity.this, "上报成功！", Toast.LENGTH_SHORT).show();
					ErrorReportActivity.this.onBackPressed();
				}
			}

			@Override
			public void getDataFailed() {
				// 这里仅作演示，实际请求失败后怎么操作根据实际情况来看

			}

		}, ErrorReportActivity.this);
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent;
		switch (v.getId()) {

			case R.id.photo_btn: //照相 全景图
				
				getFileName();
				File imageFile = new File(fileName);// 通过路径创建保存文件
				imageUri = Uri.fromFile(imageFile);
				
				intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);
				startActivityForResult(intent, 100);
				
				break;
				
			case R.id.submit_btn: 
				this.report();
				break;
			default:
				break;
		}
	}

	/**
	 * 获取上传文件路径
	 */
	protected void getFileName() {
		String rootPath;
		boolean hasSDCard = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
		if (hasSDCard) {
			rootPath = Environment.getExternalStorageDirectory().toString();
		} else {
			rootPath = Environment.getDownloadCacheDirectory().toString();
		}

		String filePath = rootPath + File.separator + this.getPackageName()
				+ File.separator + "images";

		File file = new File(filePath);
		if (!file.exists())
			file.mkdirs();
		fileName = file.getPath() + File.separator + new Date().getTime() + ".jpg";

	}
	
	@Override
	protected void loadViewLayout() {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_error_report);
	}

	@Override
	protected void findViewById() {
		// TODO Auto-generated method stub
		consistentRadio = (RadioButton)this.findViewById(R.id.consistent_true_rb);
		remarkEdt = (EditText)this.findViewById(R.id.remark_et);
		photoImv = (ImageView)this.findViewById(R.id.picture_imv);
		photoBtn = (Button)this.findViewById(R.id.photo_btn);
		submitBtn = (Button)this.findViewById(R.id.submit_btn);
	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub
		photoBtn.setOnClickListener(this);
		submitBtn.setOnClickListener(this);
	}

	@Override
	protected void processLogic() {
		// TODO Auto-generated method stub

	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case 100:
				if(imageUri != null){
					initBitmap();
					photoImv.setImageURI(imageUri);
					photoImv.setLayoutParams(new LayoutParams(photoImv.getLayoutParams().width, photoImv.getLayoutParams().width*16/9));
					
				}
				break;
			}
		}
	}
	
	private void initBitmap(){
		DisplayMetrics metric = new DisplayMetrics();
		this.getWindowManager().getDefaultDisplay().getMetrics(metric);
		int screenWidth = metric.widthPixels;  
		int screenHeight = metric.heightPixels;
	
		BitmapFactory.Options facOpt = new BitmapFactory.Options();
		facOpt.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(fileName,facOpt);//此时返回bm为空
		
		facOpt.inJustDecodeBounds = false;
		int w = facOpt.outWidth;
		int h = facOpt.outHeight;
		
		float hh = 600f;//这里设置高度为600f
		float ww = hh * screenWidth / screenHeight;
		
		//缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;//be=1表示不缩放
		if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
			be = (int) (facOpt.outWidth / ww);
		} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
			be = (int) (facOpt.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		facOpt.inSampleSize = be;//设置缩放比例
		//重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		bitmap = BitmapFactory.decodeFile(fileName, facOpt);
			
		FileOutputStream fOut = null;
        try {
                fOut = new FileOutputStream(fileName);
        } catch (FileNotFoundException e) {
                e.printStackTrace();
        }
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        try {
                fOut.flush();
        } catch (IOException e) {
                e.printStackTrace();
        }
        try {
                fOut.close();
        } catch (IOException e) {
                e.printStackTrace();
        }

	}
}
